<template>
	<view>
		<u-navbar back-text="" 
		:leftIconColor="tksetting.titlecolor" 
		:bgColor="tksetting.color" 
		:titleStyle="{color:tksetting.titlecolor}" 
		:title="title"  :autoBack="true"  
		:placeholder="true">
			
		</u-navbar>
	<view class="content">
		<!-- 轮播图区域 -->
		<swiper class="swiper" :style="{ height: swiperHeight + 'px' }" :duration="swiperDuration" :circular="true"
			:vertical="swiperVertical"
			:current="swiperCurrent" @change="swiperChange">
			<swiper-item class="swiper-item" v-for="(json, index) in swiperList" :key="index">
				<view class="page-item" v-if="json.index != null">
					<!-- <view class="menu">
						<view class="left">{{ json.index + 1 }} / {{ mount }}</view>
						<view class="right" v-if="mode == 1" @click="tip">
							  <u-icon name="eye"></u-icon>
						</view>
						<view class="right" v-if="mode == 0" @click="setAutoplay">
							<text v-if="!swiperConfig.autoplay">自动</text>
							<text v-else>停止</text>
						</view>
					</view> -->
					
					<view class="title-info">
						<text :class="'type type-' + json.classid">{{ getType(json.classid) }}</text>
						<rich-text :nodes="json.question"></rich-text>
					</view>
					<!-- 单选题和判断题 -->
					<radio-group v-if="json.classid == '1' ||  json.classid == '3'" class="options" @change="radioChange">
						<label class="option flex-box" v-for="(value, key) in json.daan"
							:class="{ checked: json.checked.includes(key), wrong: !json.isRight }" :key="key">
							<radio class="radio" style="margin-right:10rpx;display:none;" :disabled="json.disabled"
								:value="key" :checked="json.checked.includes(key)" />
							<view class="option-head">{{ upPer(key)}}</view>
							<view v-if="ispic(value)" class="option-body">
									<u--image
									style="text-align: left;"
									:showLoading="true"
									radius="12"
									:src="value"
									mode="heightFix"
									height="120px"
								    ></u--image>
							</view>
							<view v-else  class="option-body">{{ value }}</view>
							
						</label>
					</radio-group>

					<!-- 多选题 -->
					<checkbox-group v-if="json.classid == '2'" class="options" @change="checkboxChange">
						<label class="option flex-box" v-for="(value, key) in json.daan" :class="{
								checked: json.checked.includes(key),
								wrong: json.finish && !json.isRight
							}" :key="key">
							<checkbox class="checkbox" style="margin-right:10rpx;display:none;"
								:checked="json.checked.includes(key)" :disabled="json.disabled" :value="key"/>
							<view class="option-head">{{ upPer(key) }}</view>
							<view v-if="ispic(value)" class="option-body">
									<u--image
									style="text-align: left;"
									:showLoading="true"
									radius="12"
									:src="value"
									mode="heightFix"
									height="120px"
								    ></u--image>
							</view>
							<view v-else  class="option-body">{{ value }}</view>
							
						</label>
						<view :class="[
								'check-confirm',
								json.userAnswer.length > 1 && !json.finish ? 'hightlight' : ''
							]" v-if="!json.show" @click="checkConfirm">
							确定答案
						</view>
					</checkbox-group>
					
					<!-- 问答题 -->
					<view class="uni-textarea options" v-if="json.classid == '4' || json.classid == '5' ">
								<textarea style="background: #eaeaea; width: 100%; padding: 12rpx;"  @input="onInput" :value="json.userAnswer" :disabled="json.disabled" />
								<view :class="[
										'check-confirm',
										json.userAnswer.length > 1 && !json.finish ? 'hightlight' : ''
									]" v-if="!json.show" @click="checkConfirm_wd">
									确定答案
								</view>
					</view>
					<!-- 答案与解析 -->
					<u-card 
					:border='false'
					:head-border-bottom="false"
					:foot-border-top="false"
					:full="true" 
					:title-color="json.finish && !json.isRight?'#dd524d':'#5ac725'" 
					v-if="json.show" :title="`正确答案 `+ upPer(json.answer)"
					:head-style="{'font-weight': '600'}"
					>
					<view class="" slot="body">
						<u-button  @click="nextPage" text="下一题"></u-button>
					</view>
					
					</u-card>
					
				</view>
			</swiper-item>
		</swiper>
		<!--<view class="page" v-if="!swiperConfig.autoplay">
			<view @click="lastPage">上一题</view>
			<view @click="nextPage">下一题</view>
		</view> -->
		<!-- 底部操作区域 -->
	</view>
	
	<u-modal 
		:show="mask" :title="`正确答案 `+ upPer(question.answer)" :closeOnClickOverlay="true" confirmText="下一题" :showCancelButton="true"
		duration="0"
		@cancel="cancel"
		@confirm="confirm"
	>
		<view class="slot-content">
			<rich-text :nodes="`解析:`+question.analysis"></rich-text>
		</view>
	</u-modal>
	
	
	<!-- 答题卡 弹出层 -->
	<!-- <view v-show="qusCard">
		<my-popup-card :top="top_num" :color="tksetting.color" :questions="questions" mode="0" @close="qusCard = false" @swiperTo="initSwiper($event)">
		</my-popup-card>
	</view> -->
	
	</view>
</template>

<script>
	import {toast,showModal, isImageUrlByExtension,clearStorageSync, setStorageSync, getStorageSync, useRouter} from '@/utils/utils.js'
	import swiper from '@/utils/swiper.js';
	import { mapState } from 'vuex';
	export default {
		data() {
			return {
			
				bijishow:false,
				// mode 1：表示普通做题模式 0：表示背题模式
				mode: null,
				text: '',
				keys:'',
				update:'',
				id: '',
				title: '知识问答',
				// 题目总数
				mount: '',
				// 用户是否能够购买
				have: '',
				// 题目列表
				questions: [],
				// 当前题目
				question: {},
				// 当前swiper渲染的items
				swiperList: [],
				// 滑动到的位置
				swiperIndex: 0,
				// 此值控制swiper的位置
				swiperCurrent: 0,
				// 值为0禁止切换动画
				swiperDuration: 250,
				// 需要几个swiperItem, 最少值为3,如果有分页的需求，可以是10、20, 任何
				swiperListLength: 4,
				// swiper 的个人设定
				swiperConfig: {
						tc:false,
						zdqh:false,
						fx:false,
						ytfx:false,
						interval:false,
						ksfx:false,
						audio:false,
						autoplay: false
					},
				lastIndex: 0,
				lastShow: false,
				// 是否显示错误提示
				mask: false,
				// 是否显示答题卡  微信  方便客服与你联系
				qusCard: false,
				time: 0,
				audios:null,
				//测试数据
				headHeight:'',
				
			};
		},

		async onLoad(opt) {
			
			console.log(this.shebei_info)
			
			await this.init();
			uni.setNavigationBarTitle({
			      title: this.title
			    });
			
		},
		onUnload() {
			
		},
		mounted(){
			  this.setting.forEach(item => {
			    this.swiperConfig[item.name] = item.value;
			});
		},
		onHide() {
			
		},
		beforeDestroy(){
			
		},
		computed: {
			...mapState(['user','shebei_info','tksetting','setting']),
			swiperVertical() {
				if (this.mode == 1 && this.swiperConfig) {
					return this.swiperConfig.fx;
				} else if (this.mode == 0 && this.swiperConfig) {
					return this.swiperConfig.ytfx;
				}
				return false;
			},
			zql() {
			   const { dui, cuo } = this.question;
			   // 使用 Number() 函数强制转换为数字
			   const duiNum = Number(dui);
			   const cuoNum = Number(cuo);
			   const totalAttempts = duiNum + cuoNum;
			   const correctRate = totalAttempts > 0 ? Math.floor((duiNum / totalAttempts) * 100) : 0;
			   return correctRate
			  },
			  top_num(){
				 return this.shebei_info.safeArea.top
			  },
			  sc_num(){
				  return this.question.Collection?1:"";
			  },
			  swiperHeight(){
				  return Number(this.shebei_info.safeArea.height ?? 0) - Number(this.shebei_info.safeArea.top ?? 0) - Number(this.shebei_info.statusBarHeight ?? 0) - 44;
			  }
		},

		methods: {
			async init() {
				const that = this;
				await that.getData();
				
				await this.initSwiper(this.lastIndex)
				if (this.mode == 0) {
					this.tip();
				} else {
					this.runtime();
				}
			},
			async getData() {
				let that = this;
				const data = await this.$api.zuoti({zid: 9});
				if (data.code == 0) {
					this.have = data.have || false;
					this.keys=data.nickname;
					this.mount = data.row;
					this.text = data.text;
					this.nickname = data.nickname;
					// 初始化swiper配置项
					this.lastIndex = 0
					//this.time = data.sj.kssj || 90 * 60
					// 初始化问题列表
					let questions = data.data;
					for (let [item, index] of questions.map((item, index) => [item, index])) {
						item.index = index;
						this.setData(item);
						// this.setDataForTest(item);
					}
					this.questions = questions;
				
				} else {
					let res = await  showModal({
						content: data.msg,
					});
					if (res) {
						uni.navigateBack();
					}
				}
			},
			setLocalData(localData) {
				localData = JSON.parse(localData)
				for (let key in localData) {
					this[key] = localData[key]
				}
			},
			setData(obj) {
				let initObj = {
					show: false,
					userAnswer: '',
					isRight: '',
					disabled: false,
					finish: false,
					checked: ''
				};
				obj = Object.assign(obj, initObj);
			},
			// 初始化swiperlist
			initSwiper(lastIndex) {
				const that = this;
				that.swiperList = swiper.initSwiperList(that, lastIndex);
				
			},
			runtime() {
				setInterval(() => {
					this.time++;
				}, 1000);
			},
			goLast() {
				this.initSwiper(this.lastIndex);
				//this.lastShow = false;
			},
			// 监听swiper改变
			swiperChange(e) {
				const that = this;
				let current = e.detail.current;
				const timu=swiper.changePage(that, current);
				console.log(timu)
				if(timu=='end'){
					this.init();
				}
				if (that.mode == 0) {
					that.tip();
				}
			},
			// 上一题
			lastPage() {
				this.swiperCurrent = this.swiperIndex > 0 ? this.swiperIndex - 1 : this.swiperListLength - 1;
			},
			// 下一题
			nextPage() {
				this.swiperCurrent = this.swiperIndex < this.swiperListLength - 1 ? this.swiperIndex + 1 : 0;
			},
			setAutoplay() {
				if (!this.swiperConfig.autoplay) {
					uni.showToast({
						title: `开启自动滑题,当前每${this.swiperConfig.interval}秒自动滑动一题,个人中心可以设置`,
						icon: 'none'
					});
					this.swiperConfig.autoplay = true;
				} else {
					uni.showToast({
						title: `已关闭自动滑题`,
						icon: 'none'
					});
					this.swiperConfig.autoplay = false;
				}
			},
			// 根据typeid判断题目类型
			getType(typeId) {
				let type = '';
				switch (typeId) {
					case '1':
						type = '单选题';
						break;
					case '2':
						type = '多选题';
						break;
					case '3':
						type = '判断题';
						break;
					case '4':
						type = '问答题';
						break;
					case '5':
					    type = '填空题';
					break;
				}
				return type;
			},
			upPer(str){
				if(str){
					return str.toUpperCase()
				}
			},
			// 点击提示按钮
			tip() {
				if (!this.question.show) {
					this.question.disabled = true;
					this.question.isRight = true;
					this.checkBy(this.question.answer);
					this.question.show = true;
				}
			},
			// 通过代码选中正确答案，点击提示按钮时会用到此函数
			checkBy(answer) {
				this.question.checked = answer;
			},

			maskControll() {
				// 判断用户的答案与标准答案是否匹配
				let swiperConfig = this.swiperConfig;
				let question = this.question;
				if (question.isRight) {
					if (swiperConfig.zdqh) {
						this.nextPage();
					}
				} else {
					
					if (swiperConfig.tc) {
						this.mask = true;
					}
				
					if (swiperConfig.audio) {
						this.audios.src= question.audio;
						this.audios.play();
					}
				}
			},
			async _optChange() {
				const that = this
				// 本地存储记录
				const record = {
					mount: this.mount,
					text: this.text,
					title: this.title,
					nickname:this.nickname,
					//swiperConfig: this.swiperConfig,
					questions: this.questions,
					time: this.time,
					lastIndex: this.question.index
				}
				// 提交数据
				this.question.finish = true;
				this.question.isRight = this.question.answer == this.question.userAnswer ? true : false;
				
			
				//uni.setStorageSync(this.storageKey, JSON.stringify(record))
				//this.nextPage();
			},
			// 单选题选择
			async radioChange(e) {
				
				const that = this;
				const question = that.question;
				this.checkBy(e.detail.value);
				// 获取到当前选项的值
				this.question.userAnswer = e.detail.value;
				this.question.isRight = this.question.answer == e.detail.value ? true : false;
				this.question.isRight ? this.question.dui++ : this.question.cuo++;
				
				//console.log(this.question)
				
				// 点击后禁用单选按钮
				this.question.disabled = true;
				this.question.finish = true;
				this.question.show = true;
				this.maskControll();
				await this._optChange()
				const jifen= await this.$api.record({
							tid: question.id,
							zid: question.zid,
							text: that.text,
							type: that.question.isRight ? 1 : 2
				})
				if(jifen.code==1){
					toast(jifen.msg);
				}
			},
			// 多选题选择
			checkboxChange(e) {
				let userAnswer = e.detail.value.sort().join('');
				this.question.userAnswer = userAnswer;
				// this.question.temp = userAnswer
				this.checkBy(userAnswer);
			},
			//填空题填写绑定
			onInput(e){
				let userAnswer = e.detail.value;
				this.question.userAnswer = userAnswer;
			}
			,
			// 确定多选题的选项
			async checkConfirm() {
				
				const that = this;
				let question = this.question;
				if (this.question.userAnswer && this.question.userAnswer.length > 1) {
					
					this.question.disabled = true;
					this.question.finish = true;
					this.question.show = true;
					this.question.isRight = this.question.answer == this.question.userAnswer ? true : false;
					this.question.isRight ? this.question.dui++ : this.question.cuo++;
					this.maskControll();
					this._optChange()
					const jifen= await this.$api.record({
								tid: question.id,
								zid: question.zid,
								text: that.text,
								type: that.question.isRight ? 1 : 2
					})
					
					if(jifen.code==1){
						toast(jifen.msg);
					}
					
				} else {
					toast({
						title: '多选题至少选择两个答案',
						icon: 'none'
					});
				}
			},
			
			checkConfirm_wd() {
				
				const that = this;
				let question = this.question;
				if (this.question.userAnswer && this.question.userAnswer.length > 1) {
					
					this.question.disabled = true;
					this.question.finish = true;
					this.question.show = true;
					this._optChange()
					this.maskControll();
					
				} else {
					toast({
						title: '请填写答案',
						icon: 'none'
					});
				}
			},

			cancel() {
				this.mask = false;
			},
			confirm() {
				if (this.swiperConfig.audio) {
					this.audios.stop();
				}
				this.mask = false;
				this.nextPage();
			},

			navBack() {
				let that = this;
				uni.showModal({
					title: '系统提示',
					content: '你确定要退出吗?',
					success(res) {
						if (res.confirm) {
						  uni.navigateBack();
						}
					}
				});
			},
			ispic(url){
				return isImageUrlByExtension(url);
			}
			
		}
	};
</script>

<style lang="scss" scoped>
	@import "@/tk.scss";
</style>
